import {
  createRouter,
  createWebHistory,
} from 'vue-router';
import Me from '../views/Me.vue';
import News from '../views/News.vue';
import Loginview from '../views/Loginview.vue';
import Registerview from '../views/Registerview.vue';
import Socketview from '../views/Socketview.vue';
import Searchview from '../views/Searchview.vue';
import Newfriend from '../views/Newfriend.vue';
import Upheadimg from '../views/Upheadimg.vue';

const routes = [
  {
    path: '/',
    name: 'Me',
    component: Me,
  },
  // 我的页面路由
  {
    path: '/me',
    name: 'Me',
    component: Me,
    meta: {
      isAuth: true,
    },
  },
  // 消息页面路由
  {
    path: '/news',
    name: 'News',
    // route level code-splitting
    // this generates a separate chunk (news.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    // component: () => import (/* webpackChunkName: "news" */'../views/News.vue'),
    component: News,
    meta: {
      isAuth: true,
    },
  },
  // 登录页面路由
  {
    path: '/loginview',
    name: 'Loginview',
    component: Loginview,
  },
  // 注册页面路由
  {
    path: '/registerview',
    name: 'Registerview',
    component: Registerview,
  },
  // 消息发送页面
  {
    path: '/socketview',
    name: 'Socketview',
    component: Socketview,
    // socketview页用props接取参数
    props(route) {
      return { calltoken: route.query.calltoken };
    },
  },
  // 搜索好友页面
  {
    path: '/searchview',
    name: 'Searchview',
    component: Searchview,
  },
  // 好友申请页面
  {
    path: '/newfriend',
    name: 'Newfriend',
    component: Newfriend,
  },
  // 上传头像页面
  {
    path: '/upheadimg',
    name: 'Upheadimg',
    component: Upheadimg,
  },
];

const router = createRouter({
  // history模式
  history: createWebHistory(),
  // hash模式：#/
  // history: createWebHashHistory(),
  routes,
});

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  if (to.meta.isAuth) {
    if (window.sessionStorage.getItem('token')) {
      next();
    } else {
      // eslint-disable-next-line
      window.alert('请先登录');
    }
  } else {
    next();
  }
});

export default router;
